from flask import jsonify, send_file
from app.api.v1 import bp
from app.models.marine_area import MarineArea
from app.models.industry_score import IndustryScore
from app.models.ecological_indicator import EcologicalIndicator
import pandas as pd
import io
from datetime import datetime

@bp.route('/export/marine-area/<int:id>', methods=['GET'])
def export_marine_area(id):
    # 获取海域数据
    area = MarineArea.query.get_or_404(id)
    
    # 获取评分数据
    scores = IndustryScore.query.filter_by(marine_area_id=id).all()
    score_data = [{
        '产业类型': score.industry_type,
        '评分': float(score.score),
        '评估日期': score.evaluation_date
    } for score in scores]
    
    # 获取生态指标数据
    indicators = EcologicalIndicator.query.filter_by(marine_area_id=id).all()
    indicator_data = [{
        '水质': float(ind.water_quality),
        '生物多样性': float(ind.biodiversity),
        '污染指数': float(ind.pollution_index),
        '资源储量': float(ind.resource_reserve),
        '环境承载力': float(ind.environmental_capacity),
        '测量日期': ind.measurement_date
    } for ind in indicators]
    
    # 创建Excel文件
    output = io.BytesIO()
    with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
        # 写入产业评分数据
        pd.DataFrame(score_data).to_excel(writer, sheet_name='产业评分', index=False)
        # 写入生态指标数据
        pd.DataFrame(indicator_data).to_excel(writer, sheet_name='生态指标', index=False)
    
    output.seek(0)
    filename = f'marine_data_{area.area_name}_{datetime.now().strftime("%Y%m%d")}.xlsx'
    
    return send_file(
        output,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        as_attachment=True,
        download_name=filename
    ) 